package com.hmdp.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

@Component
public class RedisIDWorker {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    // 时间戳的起始时间
    private static final long BEGIN_TIMESTAMP;
    static {
        LocalDateTime time = LocalDateTime.of(2025, 1, 1, 0, 0, 0);
        BEGIN_TIMESTAMP = time.toEpochSecond(ZoneOffset.UTC);
    }

    // 序列号的位数
    private static final int COUNT_BITS = 32;

    public Long nextId(String keyPrefix) {
        // 1.生成31位时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        long timestamp = nowSecond - BEGIN_TIMESTAMP;
        // 2.生成32位序列号
        String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));   // 格式像这样=> 2025:01:01
        // 因为我们用long而不是Long接收，所以这里警告可能会出现空指针异常，实际上不会，increment函数会在key不存在时自动创建一个key，并返回0
        long count = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + date);

        // 3.拼接并返回
        return timestamp << COUNT_BITS | count;
    }
}

